package com.org.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.blockchain.API.TimeCoinAPI;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.org.mapper.NormalUserMapper;
import com.org.pojo.NormalUser;
import com.org.common.PageBean;
import com.org.service.NormalUserService;
import com.org.utils.Md5Util;
import com.org.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.InvalidAlgorithmParameterException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;

import static com.blockchain.API.TimeCoinAPI.adminPK;

/**
 * ClassName: NormalUserServiceImpl
 * Package: com.org.service.impl
 * Description:
 *
 * @Author Origin
 * @Create 2024/2/2 0:47
 * @Version 1.0
 */
@Service
public class NormalUserServiceImpl extends ServiceImpl<NormalUserMapper, NormalUser> implements NormalUserService {

    @Autowired
    private NormalUserMapper normalUserMapper;

    @Override
    public NormalUser findByUsername(String username) {
        NormalUser n = normalUserMapper.findByUsername(username);
        return n;
    }

    @Override
    public void register(NormalUser normalUser) throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException {
        normalUser.setCreateTime(LocalDateTime.now());
        normalUser.setUpdateTime(LocalDateTime.now());

//        normalUser.setState("待审核实名认证信息");

//        int yearBirth = Integer.parseInt(normalUser.getIdentityId().substring(6, 10));
//
//        normalUser.setAge(2024 - yearBirth);
//        normalUser.setUserType(1);
//        normalUser.setIsOldman(1);
//        normalUser.setIsVolunteer(1);
        //生成密钥
        String userPK = TimeCoinAPI.userRegister();
        normalUser.setChainKey(userPK);

        normalUserMapper.insert(normalUser);
    }

    @Override
    public void update(NormalUser normalUser) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        normalUser.setId(id);
        normalUserMapper.update(normalUser);
    }

    @Override
    public void updateAvatar(String avatarUrl) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        normalUserMapper.updateAvatar(avatarUrl, id);
    }

    @Override
    public void updatePwd(String newPwd) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        normalUserMapper.updatePwd(Md5Util.getMD5String(newPwd), id);
    }

    @Override
    public void updateIdentity(String name, String sex, String phone, String identityId, String identityIdImg) {
        Calendar calendar = Calendar.getInstance();
        int yearBirth = Integer.parseInt(identityId.substring(6, 10));
        Integer age = calendar.get(Calendar.YEAR) - yearBirth;
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        normalUserMapper.updateIdentity(name, sex, phone, identityId, identityIdImg, age, id);
    }

    @Override
    public void updateState(Integer id, String state, String level) throws Exception {
        NormalUser normalUser = normalUserMapper.selectById(id);
        //state == "已通过实名认证"
        if (state.equals("已通过实名认证") && !TimeCoinAPI.isAwardedCoin(normalUser.getChainKey(), normalUser.getChainKey())) {
            NormalUser user = normalUserMapper.selectById(id);
            String userPK = user.getChainKey();
            // 判断等级
            int awardCoin;
            if (level.equals("A")) {
                awardCoin = 40;
            } else if (level.equals("B")) {
                awardCoin = 30;
            } else if (level.equals("C")) {
                awardCoin = 20;
            } else if (level.equals("D")) {
                awardCoin = 10;
            } else {
                awardCoin = 0;
            }
            normalUserMapper.updatestate(id, "实名信息处理中");
            // 发行
            CompletableFuture.runAsync(() -> {
                try {
                    TimeCoinAPI.awardCoin(adminPK, userPK, awardCoin);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).thenRun(() -> {  // 时间币发行完后
                normalUserMapper.updatestate(id, state);
            });
        }
        else{
            normalUserMapper.updatestate(id, state);
        }

    }

    @Override
    public PageBean<NormalUser> list(Integer pageNum,
                                     Integer pageSize,
                                     String username,
                                     String communityId,
                                     String name,
                                     String identityId,
                                     String phone,
                                     String isOldman,
                                     String isVolunteer,
                                     String sex,
                                     String state,
                                     String chainKey) {


        //1. 创建PageBean对象
        PageBean<NormalUser> pb = new PageBean<>();

        //2.开启分页查询
        PageHelper.startPage(pageNum, pageSize);

        Map<String, Object> map = ThreadLocalUtil.get();

        //3.调用mapper

        QueryWrapper<NormalUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("username", username)
                .like("name", name)
                .like("identity_id", identityId)
                .like("is_oldman", isOldman)
                .like("phone", phone)
                .like("is_volunteer", isVolunteer)
                .like("sex", sex)
                .like("state", state)
                .like("chain_key", chainKey);

        if(!Objects.equals(communityId, "")){
            queryWrapper.eq("community_id", communityId);
        }

        queryWrapper.orderBy(true, false, "create_time");

        List<NormalUser> as = normalUserMapper.selectList(queryWrapper);

        //Page中提供了方法，可以获取PageHelper分页查询后 得到的总记录条数和当页数据
        Page<NormalUser> p = (Page<NormalUser>) as;

        //把数据填充到PageBean对象中
        pb.setTotal(p.getTotal());  //总共多少页
        pb.setItems(p.getResult()); //当前页内容

        return pb;
    }

    @Override
    public void delete(Integer id) {
        normalUserMapper.deleteById(id);
    }


    @Override
    public NormalUser getInfoById(Integer id) {
       return  normalUserMapper.selectById(id);
    }
}
